package com.jianyun.jyzs.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.JsResult;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.bean.IntegratedResult;
import com.jianyun.jyzs.http.IShttpHelper;
import com.jianyun.jyzs.utils.LoginCache;
import com.jianyun.jyzs.utils.UtilsStyle;
import com.jianyun.jyzs.widget.IntegratedPopu;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import com.jianyun.jyzs.utils.RceLog;

/**
 * 综合业务接 界面
 * Created by yangshijun on 2018/5/29.
 */

public class IntegratedServiceActivity extends AppCompatActivity
        implements View.OnClickListener, AdapterView.OnItemClickListener , IShttpHelper.IsOptionListener {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.webView)
    WebView webView;

    private String erpRootUrl;
    private String userId;
    private String enterpriseCode;
    private ProgressDialog dialog;
    private String url;//页面URL
    private String webid = "134";
    private List<IntegratedResult> response = null;
    private IntegratedPopu popu;
    private boolean popu_tag = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.jyb_activity_webview);
        ButterKnife.bind(this);
        initData();
        initView();
        initWebView();
    }


    private void initData() {
        erpRootUrl = LoginCache.getInstance().getLoginCache().getErpRootUrl();
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        url = erpRootUrl + "JiChengLogin.aspx?userid=" + userId + "&urlStr=jybwebapp/appindex.html?" + "|apptype=gongdibao";
        Log.i("test","综合业务："+url);
        //url = getIntent().getStringExtra("url");
    }

    private void initView() {
        dialog = new ProgressDialog(this);
        dialog.setMessage("loading...");
        topBack.setVisibility(View.VISIBLE);
        topText.setVisibility(View.VISIBLE);
        ivMoreLinearLayout.setVisibility(View.VISIBLE);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setUseWideViewPort(true);
        webView.getSettings().setLoadWithOverviewMode(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setSupportZoom(true);
        webView.setWebViewClient(new OAWebViewClient());
        webView.setWebChromeClient(new OAWebChromeClient());
        webView.getSettings().setDomStorageEnabled(true);
        webView.setDownloadListener(new MyWebViewDownLoadListener());
        ivMoreLinearLayout.setOnClickListener(this);
        topBack.setOnClickListener(this);
        topCreat.setOnClickListener(this);
    }
    private void initWebView() {
        webView.loadUrl(url);
        dialog.setCancelable(false);
        IShttpHelper.getIsOption("GetWebIdList", userId, this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_moreLinearLayout:
                if (popu_tag) {
                    //子页面有操作
//                    IntegratedPopu2 integratedPopu2 = new IntegratedPopu2(this);
//                    integratedPopu2.showPopupWindow(ivMoreLinearLayout);
                    url = erpRootUrl + "JiChengLogin.aspx?userid=" + userId+ "&urlStr=jybwebapp/appindex.html?" + "|apptype=gongdibao";
                    webView.loadUrl(url);
                } else {
                    if (null != response && response.size() > 0) {
                        popu = new IntegratedPopu(this, response, this);
                        if (null!=popu&&ivMoreLinearLayout!=null){
                            popu.showPopupWindow(ivMoreLinearLayout);
                        }
                    }
                }
                break;
            case R.id.topBack:
                //finish();
                if (topText.getText().toString().equals("综合业务")){
                    finish();
                }else {
                    webView.goBack();
                }
                break;
            case R.id.topCreat:

                break;
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //popuwindow
        if (response != null & response.size() > 0) {
            webView.clearHistory();
            url = erpRootUrl + "JiChengLogin.aspx?userid=" + userId + "&urlStr=jybwebapp/appindex.html?webid=" + response.get(position).getWebID() + "|apptype=gongdibao";
            RceLog.d("lml", "url===" + url);
            webView.loadUrl(url);
            if (popu.isShowing() & popu != null) popu.dismiss();
        }
    }


    @Override
    public void option(List<IntegratedResult> list) {
        if (list.size() > 0) {
            response = list;
        }
    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    class MyWebViewDownLoadListener implements DownloadListener {
        @Override
        public void onDownloadStart(String s, String s1, String s2, String s3, long l) {
            Uri uri = Uri.parse(s);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }
    class OAWebViewClient extends WebViewClient {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            dialog.show();
            view.loadUrl(url);
            return false;
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            dialog.dismiss();
            appHideBar();
            String call = "javascript:isChildFlag";

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                webView.evaluateJavascript(call, new ValueCallback<String>() {

                    @Override
                    public void onReceiveValue(String value) {
                        popu_tag = value != null & value.equals("true") ? true : false;
                        if (popu_tag){
                            ivMore.setImageResource(R.drawable.chat_vc_icon_nav_bar_group_btn_default);
                        }else {
                            ivMore.setImageResource(R.mipmap.ic_more);
                        }
                    }
                });
            } else {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        String call = "javascript:getisChild()";
                        webView.loadUrl(call);
                    }
                });

            }
        }
    }


    public void appQuery() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript("javascript:appQueryShow()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {

                }
            });
        } else {
            webView.loadUrl("javascript:appQueryShow()");
        }
    }




    public void appNewRecord() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript("javascript:newrecord1()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {

                }
            });
        } else {
            webView.loadUrl("javascript:newrecord1()");
        }
    }
    public void appHideBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            webView.evaluateJavascript("javascript:hideBar()", new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {

                }
            });
        } else {
            webView.loadUrl("javascript:hideBar()");
        }
    }

    private class OAWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {
            // Log.i("test","title:"+title);
            if (topText != null && !TextUtils.isEmpty(title)) {
                topText.setText(title);
            }
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
            RceLog.d("lml","onJsAlert message = "+message);
            if (message != null & message.equals("true")) {
//                ToastUtil.showToast(IntegratedServiceActivity.this,""+message);
                popu_tag = message != null & message.equals("true") ? true : false;

            }
            result.cancel();
            return true;
        }


    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {

            if (topText.getText().toString().equals("综合业务")){
                finish();
            }else {
                webView.goBack();
                return true;
            }
        }

        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        cleanCooker();
    }

    private void cleanCooker() {
        CookieSyncManager.createInstance(this);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();
        webView.setWebChromeClient(null);
        webView.setWebViewClient(null);
        webView.getSettings().setJavaScriptEnabled(false);
        webView.clearCache(true);
    }


}
